import router from './index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { setStore } from "@/utils/store"
import { encryptData } from '@/assets/js/encrypt';
import store from '@/store'; // 路径根据你的项目结构调整

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', "/login1", '/auth-redirect', '/bind', '/register', '/zxht']

const loginForm = {
  loginName: "admin",
  password: "123456",
}

function handlePwd(fn) {
  let form = Object.assign({}, loginForm, {
    password: encryptData(loginForm.password),
  }, {
    "captchaCode": "1",
    "captchaUuid": "90cdf4372a1b431eaf5f10ff6cda327b",
    "loginDevice": 1
  });
  store.dispatch("pwdLogin", form)
    .then(() => {
      setStore({
        type: 1,
        name: "userName",
        content: loginForm.username
      })
      fn()
    })
    .catch(() => {
    });
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
    }
  } else {
    // 没有token直接给他做登录操作
    // handlePwd(next)
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
